﻿using System.Collections.Generic;
using Sapit.Helpers;

namespace Sapit.Base
{
    public abstract class ResponseTimeThrottleBase
    {
        private static Dictionary<Invocation, int> throttledInvocations = new Dictionary<Invocation, int>();

        protected void ThrottleThisInvocation(Invocation invocation, int callsToSkip)
        {
            if (throttledInvocations.ContainsKey(invocation))
            {
                throttledInvocations.Remove(invocation);
            }
            throttledInvocations.Add(invocation, callsToSkip);
        }

        protected bool IsThisInvocationThrottled(Invocation invocation)
        {
            return
                throttledInvocations.ContainsKey(invocation) &&
                throttledInvocations[invocation] > 0;
        }

        protected void DecrementThrottleCounterForThisInvocation(Invocation invocation)
        {
            if (throttledInvocations.ContainsKey(invocation))
            {
                throttledInvocations[invocation] -= 1;
            }
        }

        protected void UnThrottleThisInvocation(Invocation invocation)
        {
            if (throttledInvocations.ContainsKey(invocation))
            {
                throttledInvocations.Remove(invocation);
            }
        }
    }
}
